<template>
  <div ref="layerAssociatedUpload" v-if="visible">
    <a-modal
      :getContainer="() => $refs.layerAssociatedUpload"
      :visible="visible"
      :title="`${source ? '个人文件关联上传' : `个人文件关联上传-${showType === 'ADD' ? '新建' : '修订'}`}`"
      width="800px"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <DynamicForm class="mt-4" :config="dyConfig" :questions="dyQuestions" />
      <DynamicTable :tables="dyTable" :config="dyTableConfig" ref="fileRef">
        <!-- 面包屑 -->
        <template #title>
          <div>
            <a-breadcrumb>
              <template v-for="(item, index) in state.breadcrumbs" :key="index">
                <a-breadcrumb-item :class="index === state.breadcrumbs.length - 1 ? null : 'hierarchy'" @click="folderClick(item)">{{ item.name }}</a-breadcrumb-item>
              </template>
            </a-breadcrumb>
          </div>
        </template>
        <!-- 文件夹及文件-->
        <template #fileImg="{ record }">
          <img v-if="record.folder" class="w-11.5 h-11.5 cursor-pointer" @click="folderClick(record)" src="@/assets/img/fileImg/filePersonalFolder.png" alt="" />
          <img v-else class="w-11.5 h-11.5 cursor-pointer" :src="checkFileIcon(record.suffix)" alt="" />
        </template>
        <template #fileName="{ record }">
          <div>
            <p class="text-4 text-black text-opacity-65 cursor-pointer" style="margin: 0">
              <span v-if="record.folder" @click="folderClick(record)">{{ record.name }}</span>
              <span v-else>{{ record.name }}</span>
            </p>
          </div>
        </template>
        <template #size="{ record }">
          <div class="fix-margin content">
            <p>{{ changeByte(record.size) }}</p>
          </div>
        </template>
        <template #modifier="{ record }">
          <div class="fix-margin content">
            <!-- <p>修改人</p> -->
            <p>{{ record.modifierName }}</p>
          </div>
        </template>
        <template #updateTime="{ record }">
          <div class="fix-margin content">
            <!-- <p>修改时间</p> -->
            <p>{{ record.modifiedTime }}</p>
          </div>
        </template>
      </DynamicTable>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, getCurrentInstance, nextTick, onBeforeUnmount, reactive, ref, watch, createVNode } from 'vue';
import indexService from './associatedUploadDiaLog';
import { filter } from 'rxjs/operators';
import { DynamicForm, DynamicTable } from '@/components/public-template';
import { Api, directoryGetChildrenFolders } from '@/config/api/personFile';
import { changeByte } from '@/utils/common';
import { message } from 'ant-design-vue';
import { checkFileIcon } from '@/utils/common';

const userId = window.localStorage.getItem('LOGIN__INFO__');
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  source: {
    // 点击来源 true:档案归档申请 false:文件申请
    type: Boolean,
    default: false
  },
  data: {
    type: Object
  },
  showType: {
    type: String
  },
  showIndex: {
    type: Number
  }
});

const emit = defineEmits(['update:visible', 'fileData']);
const state: any = reactive({
  breadcrumbs: [], // 面包屑数据
  treeData: [], // 个人文件树状数据
  selectedKey: null // 选中文件夹的id
});
const dyConfig: any = {
  labelCol: 4,
  wrapperCol: 18,
  grid: 12, // 分栏
  style: 'table-form',
  cancelSave: true // 隐藏底部按钮
};

const dyTableConfig: any = reactive({
  name: 'personFile',
  queryUrl: Api.directoryQueryFolderWithFilePage,
  protType: 'post',
  isShowHeader: true,
  rowSelection: {
    type: 'radio',
    getCheckboxProps: (record) => ({
      disabled: record.folder === true
    })
  },
  params: { parentId: JSON.parse(userId).id }
});

const { proxy }: any = getCurrentInstance();
const dyQuestions: any = reactive(indexService.getQuestions());
const dyTable: any = reactive(indexService.getTables());

const subscribeSub = proxy.$NotificationFormSub
  .getParams()
  .pipe(filter((res) => res !== 0))
  .subscribe((item: any) => {
    try {
      if (item.key === 'INPUTSERVE' && item.value.key === 'name') {
        // 条件查询全部文件
        dyTableConfig.params.parentId = '';
      } else if (item.key === 'SEARCHSERVE' && !item.value?.name) {
        // 重置回到面包屑定位
        dyTableConfig.params.parentId = state.selectedKey;
      }
    } catch (error) {
      message.error(error);
    }
  });

// 点击文件夹
const fileRef = ref(null);
function folderClick(node) {
  dyTableConfig.params.parentId = node.id;
  state.selectedKey = node.id;
  let finalData = breadcrumb(state.treeData, node.id);
  state.breadcrumbs = finalData;
  fileRef.value.getData();
}

// 获取个人文件目录
onMounted(() => {
  getFolderTree();
});
function getFolderTree() {
  directoryGetChildrenFolders({ name: '' }).then((result) => {
    if (result.success) {
      state.treeData = result.data;
    }
  });
}

//面包屑
function breadcrumb(arr: any, key: any, finalData: Array<any> = []) {
  for (let i = 0, len = arr.length; i < len; i++) {
    finalData.push({ name: arr[i].name, id: arr[i].id });
    if (arr[i].id === key) {
      return finalData;
    } else if (arr[i].children && arr[i].children.length >= 1) {
      if (breadcrumb(arr[i].children, key, finalData) != false) return finalData;
    }
    finalData.pop();
  }
  return false;
}

// 确定上传
function handleOk() {
  const obj = Object.assign({}, props.data);
  const file = fileRef.value.selectedRows[0];
  if (!file || file?.folder) {
    message.warning('请选择一项文件上传');
    return;
  }
  if (props.source) {
    obj.attachment = {
      sourceId: file.id,
      fileId: file.id,
      name: file.name,
      size: file.size,
      fileSource: 2
    };
  } else {
    if (props.showType === 'ADD') {
      obj.isShowIcon = true;
      obj.newVersionId = file.id;
      obj.attachment[0] = { attachmentFile: file.name, size: file.size, remark: '', createdTime: file.createdTime, fileId: file.id, fileSource: 2 }; // 文件来源 2:个人文件;
      console.log(obj, fileRef.value.selectedRows[0]);
    } else if (props.showType === 'REVISE') {
      obj.newVersionId = file.id;
      obj.versions = obj.versions.filter((item) => item.id !== file.id);
      obj.versions.push({
        attachmentFile: file.name,
        size: file.size,
        remark: '',
        createdTime: file.createdTime,
        flag: true,
        index: props.showIndex,
        id: file.id,
        fileSource: 2
      });
      console.log(obj, fileRef.value.selectedRows[0], 999);
    }
  }
  emit('fileData', obj);
  emit('update:visible', false);
}

// 取消弹窗
function handleCancel() {
  emit('update:visible', false);
}
onBeforeUnmount(() => {
  subscribeSub && subscribeSub.unsubscribe();
  proxy.$NotificationFormSub.clearParams();
});
</script>

<style lang="less" scoped>
.content {
  @apply text-black text-opacity-45;
  p:nth-child(2) {
    display: inline-block;
  }
}
/deep/.ant-radio-wrapper-disabled {
  display: none;
}
.fix-margin {
  p {
    margin: 0px !important;
  }
}
.hierarchy {
  cursor: pointer;
}
.hierarchy:hover {
  color: #409eff;
}
</style>
